import API from "@/common/api.js"
import store from '@/store';
//需要绑定手机号(伪登录)的路由
const needLoginArr = [
	'my/order-list',
	'jianli/jianli',
	'jianyi/jianyi',
	'my/my-xuqiu'
]
//登录
export const login = (callback) => {
	// loading(6000)
	uni.login({
		success: (e) => {
			API.getJson('users_miniLogin', {
				code: e.code
			}).then(res => {
				store.commit('$setStore', res.data);
				callback(res.data)
			}, err => {
				console.log(err);
			})
		}
	})
}



//获取用户信息
export const get_userInfo = (callback) => {
	let localStorage = uni.getStorageSync('localStorage');
	let token = localStorage.token;
	API.getJson('users_userInfo', {
		token
	}).then((res) => {
		store.commit('$setStore', res.data);
		if (!empty(callback)) {
			callback(res.data)
		}
	})
}
//修改tabbar购物车数量
export const updata_car_count = () => {
	API.getJson('gouwuche_lists', {}).then(res => {
		if (res.code == 1) {
			let count = 0;
			if (res.data.length > 0 && res.data[0].list.length > 0) {
				count = res.data[0].list.reduce((total, current) => {
					return total + parseFloat(current.num);
				}, 0)
				store.state.cartNum = count;
				uni.setTabBarBadge({
					index: 2,
					text: String(count)
				})
			} else {
				uni.removeTabBarBadge({
					index: 2
				})
			}
		}
	})
}
//历史记录
export const history_arr = (type = 'get', value = '') => {
	let arr = uni.getStorageSync('history_arr')
	let length = 12; //储存的最大条数
	if (empty(arr)) {
		arr = []
		uni.setStorageSync('history_arr', arr)
	}
	if (type == 'get') {
		return arr
	} else if (type == 'push') {
		if (arr.length < length) {
			arr.unshift(value)
		} else {
			arr.unshift(value)
			arr.splice(length, 1)
		}
		uni.setStorageSync('history_arr', arr)
		return arr
	} else if (type == 'clear') {
		uni.setStorageSync('history_arr', [])
	}
}
//跳转tab页面
export const to_switch = (route = 'index/index') => {
	let url = '/pages/' + route
	uni.switchTab({
		url: url
	});
}
//普通页面跳转
export const to_link = (route, root = 'pages') => {
	let user_info = uni.getStorageSync('user_info')
	var value = route
	if (value.indexOf('?') != -1) {
		value = (value.split('?'))[0]
	}
	console.log(needLoginArr.indexOf(value), user_info.mobile, '000')
	if (needLoginArr.indexOf(value) != -1 && (user_info.mobile == 0 || user_info.mobile == undefined)) {
		route = 'login/login'
		let url2 = '/pages/' + route
		msg('请先登录');
		setTimeout(() => {
			uni.navigateTo({
				url: url2
			});
		}, 1000)
		return false;
	}

	// if (needLoginArr.indexOf(value) != -1 && value != 'shequ/shequ' && user_info.shequ_id == 0) {
	// 	route = 'shequ/shequ'
	// 	let url3 = '/pages/' + route
	// 	msg('请先选择社区');
	// 	setTimeout(() => {
	// 		uni.navigateTo({
	// 			url: url3
	// 		});
	// 	}, 1000)
	// 	return false;
	// }

	let url = '/' + root + '/' + route
	uni.navigateTo({
		url: url
	});
}

//普通页面跳转
export const to_linkA = (route, root = 'pagesA') => {
	let user_info = uni.getStorageSync('user_info')
	var value = route
	if (value.indexOf('?') != -1) {
		value = (value.split('?'))[0]
	}
	if (needLoginArr.indexOf(value) != -1 && user_info.if_edit_phone == 0) {
		route = 'bind_phone/bind_phone'
		let url2 = '/pages/' + route
		msg('请先登录');
		setTimeout(() => {
			uni.navigateTo({
				url: url2
			});
		}, 1000)
		return false;
	}

	let url = '/' + root + '/' + route
	uni.navigateTo({
		url: url
	});
}



//关闭打开新页面
export const to_redirect = (route, root = 'pages') => {
	let url = `/${root}/` + route
	console.log(url);
	uni.redirectTo({
		url: url
	});
}

export const to_back = (delta = 1) => {
	uni.navigateBack({
		delta: delta
	})
}
//弹框提示
export const msg = (title, callback, time = 1500, mask = true) => {
	uni.showToast({
		title: title || '',
		mask: mask,
		icon: 'none'
	})
	if (typeof callback == 'function') {
		setTimeout(() => {
			callback()
		}, time)
	}
}

//设置默认值
export const set_default = (val, val2 = '\t') => {
	if (empty(val)) {
		return val2;
	}
	return val;
}
//loadding弹框
export const loading = (time = 10000, msg = '加载中') => {
	uni.showLoading({
		title: msg,
		mask: 'true'
	})
	setTimeout(() => {
		uni.hideLoading()
	}, time)
}
//判断是否为空
export const empty = (str) => {
	if (str == '' || str == undefined || str == null) {
		return true
	}
	return false
}

//获取某月最后一天

export const getMonthLength = (date) => {
	let d = new Date(date);
	// 将日期设置为下月一号
	d.setMonth(d.getMonth() + 1);

	d.setDate('1');
	// 获取本月最后一天
	d.setDate(d.getDate() - 1);
	console.log(date.substr(0, 7) + '-' + d.getDate())
	return date.substr(0, 7) + '-' + d.getDate();
}

//获取时间
export const get_date = (date_format = 'YmdHis', str_chat = '-', str_char = ':') => {
	let d = new Date()
	var s = ''
	if (date_format.indexOf('Y') >= 0) {
		s += d.getFullYear()
	}
	if (date_format.indexOf('m') >= 0) {
		s += str_chat + (d.getMonth() + 1)
	}
	if (date_format.indexOf('d') >= 0) {
		s += str_chat + d.getDate() + ' '
	}
	if (date_format.indexOf('H') >= 0) {
		s += d.getHours()
	}
	if (date_format.indexOf('i') >= 0) {
		s += str_char + d.getMinutes()
	}
	if (date_format.indexOf('s') >= 0) {
		s += str_char + d.getSeconds()
	}
	return s;
}
//获取时间戳
export const get_timestamp = (time = get_date2('YYYY-MM-DD HH:mm:ss')) => {
	time = time.replace(/-/g, '/')
	let data = new Date(time);
	return parseInt(Number(data) / 1000);
}
//获取时间
export const get_date2 = (fmt = 'YYYY-MM-DD HH:mm:ss', date = new Date()) => {
	if (!date) {
		return ''
	}
	if (typeof date === 'string') {
		date = new Date(date.replace(/-/g, '/'))
	}
	if (typeof date === 'number') {
		date = new Date(date)
	}
	var o = {
		'M+': date.getMonth() + 1,
		'D+': date.getDate(),
		'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
		'H+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds(),
		'q+': Math.floor((date.getMonth() + 3) / 3),
		'S': date.getMilliseconds()
	}
	var week = {
		'0': '\u65e5',
		'1': '\u4e00',
		'2': '\u4e8c',
		'3': '\u4e09',
		'4': '\u56db',
		'5': '\u4e94',
		'6': '\u516d'
	}
	if (/(Y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') :
				'') +
			week[date.getDay() + ''])
	}
	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k])
				.length)))
		}
	}
	return fmt

}



//小程序二维码参数 转化对象  （getUnlimited 这种方式生成）
export const qrCodeQuery = (query) => {
	if (empty(query)) {
		return {}
	}
	query = decodeURIComponent(query);
	let obj = {}
	query = query.split('&')
	query.forEach((item, index) => {
		let arr = item.split('=')
		Object.defineProperty(obj, arr[0], {
			value: arr[1],
			writable: true,
			enumerable: true,
			configurable: true
		})
	})
	return obj
}

export const GetBirthday = (birthStr) => {
	console.log(birthStr)
	let birthdays = new Date(birthStr.replace(/-/g, "/"));
	let d = new Date();
	let age = d.getFullYear() - birthdays.getFullYear() - (d.getMonth() < birthdays.getMonth() || (d.getMonth() ==
		birthdays.getMonth() && d.getDate() < birthdays.getDate()) ? 1 : 0);
	return age
}

export const compareVersion = (v1, v2) => {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)

	while (v1.length < len) {
		v1.push('0')
	}
	while (v2.length < len) {
		v2.push('0')
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i])
		const num2 = parseInt(v2[i])

		if (num1 > num2) {
			return 1
		} else if (num1 < num2) {
			return -1
		}
	}

	return 0
}